package com.kuaimacode.kframework.api.service.sys;

import com.aliyuncs.utils.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.kuaimacode.kframework.common.Constant;
import com.kuaimacode.kframework.mybatis.mapper.sys.AgentOrderRewardMapper;
import com.kuaimacode.kframework.mybatis.mapper.sys.SysOpLogMapper;
import com.kuaimacode.kframework.mybatis.models.sys.AgentOrderReward;
import com.kuaimacode.kframework.mybatis.models.sys.SysOpLog;
import com.kuaimacode.kframework.util.DateUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Optional;

/**
 * @author 中元
 * @date 2019/04/02
 */
@Service
public class SysOpLogService extends ServiceImpl<SysOpLogMapper, SysOpLog> {

	@Transactional
	public boolean saveOrUpdate(SysOpLog opLog,Boolean saveOrupdateFlag){
		if (saveOrupdateFlag){
			return baseMapper.insert(opLog)>0;
		}else{
			return baseMapper.updateById(opLog)>0;
		}
	}

	public List<SysOpLog> selectOpLog(SysOpLog opLog){
		QueryWrapper<SysOpLog> queryWrapper = new QueryWrapper<>();
		if (!StringUtils.isEmpty(opLog.getRemark())){
			queryWrapper.eq("remark",opLog.getRemark());
		}
		queryWrapper.eq("user_id",opLog.getUserId());
		queryWrapper.le("date_format(created_time,'%Y-%m-%d')",opLog.getCreatedTime());
		queryWrapper.eq("type",opLog.getType());
		queryWrapper.orderByDesc("created_time");
		return baseMapper.selectList(queryWrapper);
	}

	public String countTimes(SysOpLog opLog){
		List<SysOpLog> sysOpLogs = selectOpLog(opLog);
		String times = "0";
		Double count = 0.0;
		if (CollectionUtils.isNotEmpty(sysOpLogs)){
			SysOpLog sysLog = sysOpLogs.get(0);
			if ("上线".equals(sysLog.getRemark())){
				count = Double.parseDouble(DateUtil.getDateMs(new Date(),opLog.getCreatedTime()));
				for (int i = 1; i < sysOpLogs.size(); i++) {
					SysOpLog op = sysOpLogs.get(i);
					if ("下线".equals(op.getRemark())){
						SysOpLog opdown = sysOpLogs.get(i+1);
						count += Double.parseDouble(DateUtil.getDateMs(op.getCreatedTime(),opdown.getCreatedTime()));
					}
				}
			}else{
				for (int i = 0; i < sysOpLogs.size() ; i++) {
					SysOpLog op = sysOpLogs.get(i);
					if ("下线".equals(op.getRemark())){
						SysOpLog opdown = sysOpLogs.get(i+1);
						count += Double.parseDouble(DateUtil.getDateMs(op.getCreatedTime(),opdown.getCreatedTime()));
					}
				}
			}
			return String.valueOf(count/60);
		}else{
			return "0";
		}
	}
}
